# ICC
library(pacman)
p_load(lmerTest, haven, tidyverse)

# Data
d<-read_dta(file = "Base Macias and Ponce.dta")
d$cve_mun<-substring(text = as.character(d$id_municipio), first = nchar(as.character(d$id_municipio))-2, last = nchar(as.character(d$id_municipio)))


#Municipality variation
iccFun<-function(s){
  
  # Extract var cov
  t<-as.data.frame(s$varcor)
  t<-t$vcov
  
  # Calaculate icc
  icc<-round(t[1]/(t[1]+t[2]),4)
  
  return(icc)
}

# Municipality
# fragment
sfm<-summary(lmerTest::lmer(fragment~(1|cve_mun), data=d))

# total deaths
stm<-summary(lmerTest::lmer(total_deaths~(1|cve_mun), data=d))

# inter dto deaths
sdm<-summary(lmerTest::lmer(inter_dto_kill~(1|cve_mun), data=d))

# State
# fragment
sfe<-summary(lmerTest::lmer(fragment~(1|id_estado), data=d))

# total deaths
ste<-summary(lmerTest::lmer(total_deaths~(1|id_estado), data=d))

# inter dto deaths
sde<-summary(lmerTest::lmer(inter_dto_kill~(1|id_estado), data=d))

sList<-list(sfm, stm, sdm, sfe, ste, sde)

lapply(sList, iccFun)

